//
//  LJM_SONG_Root_Sub_ViewController.m
//  wind
//
//  Created by 李金明 on 16/1/18.
//  Copyright © 2016年 李金明. All rights reserved.
//

#import "LJM_SONG_Root_Sub_ViewController.h"
#import "LJMRankSubRoot_Soner_Son_TableViewCell.h"
#import "LJMListen_Model.h"
#import "SYPMusicPlay_ViewController.h"
#import <STKAudioPlayer.h>


#define SONGUPURL @"http://api.songlist.ttpod.com/songlists/"
#define SONGDOWNURL @"?app=ttpod&v=v8.1.3.2015112716&user_id=0&mid=iPhone4S&f=f320&s=s310&imsi=&hid=&splus=7.0.4&active=1&net=2&openudid=1389d9dc18cb741587d90a5aead8646421f95dc0&idfa=C9BC818C-A0F5-4F04-8F8D-841910E08DF7&utdid=VmGiKEXHDQ0DAIL2FOnFFzxV&alf=201200&bundle_id=com.ttpod.music&latitude=&longtitude="
#define RANKUPURL @"http://api.songlist.ttpod.com/ranklists/"
#define RANKDOWNURL @"/current?app=ttpod&v=v8.1.3.2015112716&user_id=0&mid=iPhone4S&f=f320&s=s310&imsi=&hid=&splus=7.0.4&active=1&net=2&openudid=1389d9dc18cb741587d90a5aead8646421f95dc0&idfa=C9BC818C-A0F5-4F04-8F8D-841910E08DF7&utdid=VmGiKEXHDQ0DAIL2FOnFFzxV&alf=201200&bundle_id=com.ttpod.music&latitude=&longtitude="
#define CELLHEIGHT 60//CELL的高度
#define BUTTONVIEWHEIGHT 40//VIEW的高度
@interface LJM_SONG_Root_Sub_ViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UIImageView *titleImageV;
@property (nonatomic, retain) UITableView *tableV;
@property (nonatomic, retain) UIImageView *hyalineV;
@property (nonatomic, retain) UIView *headview;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, retain) UIActivityIndicatorView *testActivityIndicator;
@property (nonatomic, retain) UIApplication *application;


#pragma 音乐播放器用
@property (nonatomic, copy) NSString *playingName;

@end

@implementation LJM_SONG_Root_Sub_ViewController

- (void)set_id:(NSString *)_id
{
    if (__id != _id ) {
        
        [__id release];
        __id = [_id retain];
    }
    //获取数据
    [self getDataStr:_id];

    
    
}

- (void)dealloc
{
    self.backDelegate = nil;
    [_playingName release];
    [_testActivityIndicator release];
    [_application release];
    [_type release];
    [_dataArr release];
    [__id release];
    [_headview release];
    [_tableV release];
    [_hyalineV release];
    [_imageUrl release];
    [_titleImageV release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor =[UIColor whiteColor];
    
    //创建navigationbar
    [self creatNavigation];
    //创建个背景视图
    [self addtitleImage];
    //添加tableView
    [self addTableView];
    //添加个透明的图片当头视图
    [self addhyalineView];
    //    添加个选择视图
    [self addchangerButView];
    //添加菊花转
    [self addUIActivityIndicatorView];

}
#pragma 增加个菊花转
- (void)addUIActivityIndicatorView
{
    //    //增加个菊花转
    self.testActivityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.testActivityIndicator.backgroundColor = [UIColor blackColor];
    self.testActivityIndicator.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - 60) / 2 , [UIScreen mainScreen].bounds.size.height / 2 - 100, 60, 60);
    self.testActivityIndicator.layer.cornerRadius = 10;
    self.testActivityIndicator.layer.masksToBounds = YES;
    [self.hyalineV addSubview:self.testActivityIndicator];
    [_testActivityIndicator release];
    [self.testActivityIndicator startAnimating];
    //增加网络旁边菊花转的方法
    self.application = [UIApplication sharedApplication];
    self.application.networkActivityIndicatorVisible = YES;
    
}
#pragma 添加个选择视图
- (void)addchangerButView
{
    self.headview = [[UIView alloc] init];
    self.headview.backgroundColor = [UIColor blackColor];
    self.headview.alpha = 0.5;
    [self.hyalineV addSubview:self.headview];
    [_headview release];
    [self.headview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.mas_equalTo(self.hyalineV.mas_bottom);
        make.height.mas_equalTo(@BUTTONVIEWHEIGHT);
    }];
    
    
}
#pragma 添加tableView
- (void)addTableView
{
    self.tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 40) style:UITableViewStylePlain];
    self.tableV.backgroundColor = [UIColor clearColor];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    self.tableV.showsHorizontalScrollIndicator = NO;
    self.tableV.showsVerticalScrollIndicator = NO;
     self.tableV.rowHeight = self.view.frame.size.height - BUTTONVIEWHEIGHT - 55;
    self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableV];
    [_tableV release];
    
}
#pragma 添加个透明的图片当头视图
- (void)addhyalineView
{
    self.hyalineV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 2)];
    self.hyalineV.image = [UIImage imageNamed:@"navigationbar"];
    self.hyalineV.backgroundColor = [UIColor clearColor];
    self.hyalineV.userInteractionEnabled = YES;
    self.tableV.tableHeaderView = self.hyalineV;
    [_hyalineV release];
}
#pragma tableView的协议方法
#pragma 数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
#pragma cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *str = @"cell";
    LJMRankSubRoot_Soner_Son_TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (nil == cell) {
        cell = [[[LJMRankSubRoot_Soner_Son_TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
    }
    LJMListen_Model *model = [self.dataArr objectAtIndex:indexPath.row];
    cell.numLab.text = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
    cell.titleLab.text = model.name;
    cell.sonerLab.text = model.singerName;
    cell.sonerStr = model.singerName;
    
    return cell;
    
}
#pragma 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELLHEIGHT;
}

#pragma 点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SYPMusicPlay_ViewController *SYPMusicPlayVC = [SYPMusicPlay_ViewController shareMusicPlayVC];
    SYPMusicPlayVC.MusicsArr = self.dataArr;
    SYPMusicPlayVC.index = indexPath.row;
    LJMListen_Model *mod = nil;
    if (0 != self.dataArr) {
        mod = self.dataArr[indexPath.row];
        SYPMusicPlayVC.musicName.text = mod.name;
        SYPMusicPlayVC.singerName.text = mod.singerName;
        NSMutableDictionary *dic = mod.auditionListArr[1];
        SYPMusicPlayVC.musicURL = dic[@"url"];  // 点击的正在播放音乐的地址
    }
    if (SYPMusicPlayVC.player) {
        NSLog(@"已经有播放器");
        if (self.playingName == SYPMusicPlayVC.musicURL) {
            NSLog(@"点击的同一首音乐");
            
            switch (SYPMusicPlayVC.player.state) {
                case STKAudioPlayerStatePlaying:
                    NSLog(@"播放状态, 暂停");
                    [SYPMusicPlayVC.player pause];
                    SYPMusicPlayVC.states = 0;
                    break;
                    
                case STKAudioPlayerStatePaused:
                    NSLog(@"暂停状态, 播放");
                    [SYPMusicPlayVC.player resume];
                    SYPMusicPlayVC.states = 1;
                    break;
                    
                case STKAudioPlayerStateBuffering:
                    NSLog(@"缓冲状态");
                    break;
                    
                default:
                    break;
            }
        } else {
            NSLog(@"点击的不是同一首歌, 清空上一个播放器");
            [SYPMusicPlayVC.player stop];
            [SYPMusicPlayVC.player release];
            [SYPMusicPlayVC creatPlayerWithMusicName:SYPMusicPlayVC.musicURL];
            self.playingName = SYPMusicPlayVC.musicURL;
            SYPMusicPlayVC.states = 1;
            NSLog(@"已经创建新的播放器, 并开始播发");
            
        }
    } else {
        NSLog(@"还没有播放器");
        
        [SYPMusicPlayVC creatPlayerWithMusicName:SYPMusicPlayVC.musicURL];
        self.playingName = SYPMusicPlayVC.musicURL;
        NSLog(@"已经创建播放器");
        
    }
    
    // 发送改变状态的通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeState" object:nil];
  
    
}

#pragma 创建navigationbar
- (void)creatNavigation
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    //给navigationbar一个透明图片然后让
    self.navigationController.navigationBar.translucent = YES;
    UIImage *image = [UIImage imageNamed:@"navigationbar"];
    
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:image];
    
    
    
}

#pragma 创建个背景视图
- (void)addtitleImage
{
    self.titleImageV = [[UIImageView alloc] init];
    [self.view addSubview:self.titleImageV];
    [self.titleImageV sd_setImageWithURL:[NSURL URLWithString:self.imageUrl] placeholderImage:[UIImage imageNamed:@"zhanwei"]];
    [_titleImageV release];
    [self.titleImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(-20);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(self.view.frame.size.width);
    }];
}

#pragma 返回的动作
- (void)backAction
{
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.alpha = 1;
    [self.navigationController popViewControllerAnimated:YES];
    [self.backDelegate SubBackNavigationDelegate];
    [self.testActivityIndicator stopAnimating];
    self.application.networkActivityIndicatorVisible = NO;
    
}

#pragma 获取数据
- (void)getDataStr:(NSString *)str
{
    NSString *urlStr = nil;
    if ([self.type isEqualToString:@"SONG"]) {
         urlStr = [NSString stringWithFormat:@"%@%@%@", SONGUPURL, str, SONGDOWNURL];
    }
    if ([self.type isEqualToString:@"RANK"]) {
     urlStr = [NSString stringWithFormat:@"%@%@%@", RANKUPURL, str, RANKDOWNURL];
    }

    [LJMNetworkTool getNetWithURL:urlStr body:nil headFile:nil responseStyle:LJMResponseJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        if (nil != responseObject) {

            NSArray *arr = [responseObject objectForKey:@"songs"];
            self.dataArr = [NSMutableArray array];
            for (NSMutableDictionary *tempDic in arr) {
                NSArray *arr = [tempDic objectForKey:@"auditionList"];
                //如果有歌曲则放入数组
                if (0 != arr.count) {
                    
                    LJMListen_Model *model = [[LJMListen_Model alloc] init];
                    //装入播放的音乐
                    model.auditionListArr = [NSMutableArray arrayWithArray:[tempDic objectForKey:@"auditionList"]];
                    
                    
                    [model initWithDic:tempDic];
                    //如果有无损音乐
                    
                    
                    if (nil != [tempDic objectForKey:@"llList"] && ![[tempDic objectForKey:@"llList"] isEqual:[NSNull null]]) {
                        model.llList = [[[tempDic objectForKey:@"llList"] objectAtIndex:0] objectForKey:@"url"];
                    }
                    
                    
                    //装入作者的信息
                    model.singersArr = [NSMutableArray arrayWithArray:[tempDic objectForKey:@"singers"]];
                    
                    [self.dataArr addObject:model];
                    [model release];
                }
            }
        }
        NSLog(@"%@", self.dataArr);
#pragma 缓存数据到本地
        NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[urlStr hash]];
        // 存储的沙盒路径
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        [self.testActivityIndicator stopAnimating];
        self.application.networkActivityIndicatorVisible = NO;
        [self.tableV reloadData];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[urlStr hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 反归档
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        
        if (result) {
            NSArray *arr = [result objectForKey:@"data"];
            self.dataArr = [NSMutableArray array];
            for (NSMutableDictionary *tempDic in arr) {
                NSArray *arr = [tempDic objectForKey:@"auditionList"];
                //如果有歌曲则放入数组
                if (0 != arr.count) {
                    
                    LJMListen_Model *model = [[LJMListen_Model alloc] init];
                    //装入播放的音乐
                    model.auditionListArr = [NSMutableArray arrayWithArray:[tempDic objectForKey:@"auditionList"]];
                    
                    
                    [model initWithDic:tempDic];
                    //如果有无损音乐
                    
                    
                    if (nil != [tempDic objectForKey:@"llList"] && ![[tempDic objectForKey:@"llList"] isEqual:[NSNull null]]) {
                        model.llList = [[[tempDic objectForKey:@"llList"] objectAtIndex:0] objectForKey:@"url"];
                    }
                    
                    
                    //装入作者的信息
                    model.singersArr = [NSMutableArray arrayWithArray:[tempDic objectForKey:@"singers"]];
                    
                    [self.dataArr addObject:model];
                    [model release];
                }
            }
            [self.testActivityIndicator stopAnimating];
            self.application.networkActivityIndicatorVisible = NO;
            [self.tableV reloadData];
        } else {
            NSLog(@"error = %@", error);
        }
        
        
    }];
    
    
    
    
    
}

#pragma 跟着tabelView的随动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.tableV) {
        CGFloat flo = scrollView.contentOffset.y;
        if (flo < 0) {
            CGFloat fl = 25 + (flo / 5);
            self.titleImageV.frame = CGRectMake((flo / 5) / 2, -fl, self.view.frame.size.width - (flo / 5), self.view.frame.size.width - 2 * (flo / 5));
        }
        
        
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
